﻿using Factory.Common;
using Factory.Common.Redis;
using Factory.MasterData.MeasureUnits.Dto;
using Microsoft.VisualBasic;
using Redis.Cluster.Demo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.OpenIddict;
using Volo.Abp.Users;

namespace Factory.MasterData.MeasureUnits
{
    /// <summary>
    /// 实现计量单位接口
    /// </summary>
    public class MeasureUnitAppService : ApplicationService, IMeasureUnitAppService
    {
        /// <summary>
        /// 注入计量单位应用服务
        /// </summary>
        private readonly IRepository<MeasureUnit, int> _measureUnitAppService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="measureUnitAppService">计量单位应用服务</param>
        public MeasureUnitAppService(IRepository<MeasureUnit, int> measureUnitAppService)
        {
            _measureUnitAppService = measureUnitAppService;
        }

        /// <summary>
        /// 添加计量单位
        /// </summary>
        /// <param name="measureunit">计量单位实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> CreateAsync(MeasureUnit measureunit)
        {
            // 异步获取同名单位的记录
            var measureunitList = await _measureUnitAppService.GetListAsync(m => m.UnitName == measureunit.UnitName);

            // 检查是否已存在该单位名称
            if (measureunitList.Count > 0)
            {
                return -100;  // 表示重复，或者抛出异常等
            }

            await _measureUnitAppService.InsertAsync(measureunit);
            return 1;  // 如果需要返回插入记录的ID

        }

        /// <summary>
        /// 删除计量单位
        /// </summary>
        /// <param name="id">计量单位主键</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> DeleteAsync(int id)
        {
            await _measureUnitAppService.DeleteAsync(m => m.Id == id);
            return 1;

        }

        /// <summary>
        /// 获取计量单位列表
        /// </summary>
        /// <param name="pagrIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="unitCode">编号</param>
        /// <param name="unitName">名称</param>
        /// <returns>反对封装好的数据</returns>
        public async Task<PagedResult> GetListAsync(int pagrIndex, int pageSize, string? unitCode, string? unitName)
        {
            var mainUnits = _measureUnitAppService.GetListAsync().Result.WhereIf(!string.IsNullOrEmpty(unitCode), m => m.UnitCode.Contains(unitCode)).WhereIf(!string.IsNullOrEmpty(unitName), m => m.UnitName.Contains(unitName));

            PagedResult pagedResult = new PagedResult();
            pagedResult.RowCount = pagrIndex;
            pagedResult.PageCount = pageSize;
            pagedResult.CurrentPage = mainUnits.Count();
            pagedResult.Queryable = mainUnits.Skip((pagrIndex - 1) * pageSize).Take(pageSize).AsQueryable();
            return pagedResult;
        }

        /// <summary>
        /// 根据ID获取计量单位
        /// </summary>
        /// <param name="id">计量单位Id</param>
        /// <returns>返回对应数据</returns>
        public async Task<MeasureUnit> GetMeasureUnitOne(int id)
        {
            var measureunit = await _measureUnitAppService.FirstOrDefaultAsync(m => m.Id == id);
            return measureunit;
        }

        /// <summary>
        /// 获取计量单位详情
        /// </summary>
        /// <returns>返回对应的DTO</returns>
        public async Task<List<PrimaryUnitDto>> GetPrimaryUnit()
        {
            var measureunit = _measureUnitAppService.GetListAsync().Result;
            var primaryUnitDto = AutoMapperExt.MapToList<PrimaryUnitDto>(measureunit);
            return primaryUnitDto;
        }

        /// <summary>
        /// 更新计量单位
        /// </summary>
        /// <param name="input"></param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> UpdateAsync(MeasureUnitUpdateDto measureunitupdateDto)
        {
            //判断是否重复
            var isDuplicate = await _measureUnitAppService.FindAsync(m => (m.UnitCode == measureunitupdateDto.UnitCode && m.Id != measureunitupdateDto.Id) || (m.UnitName == measureunitupdateDto.UnitName && m.Id != measureunitupdateDto.Id));

            if (isDuplicate != null)
            {
                return -1; // 返回特定的状态码以表示重复
            }

            //获取数据
            var measureUnit = AutoMapperExt.MapTo<MeasureUnit>(measureunitupdateDto);
            _measureUnitAppService.UpdateAsync(measureUnit);
            return 1;

        }

        private static Object obj = new Object();

        /// <summary>
        /// 查询计量单位,绑定下拉框
        /// </summary>
        /// <returns>返回结果</returns>
        public async Task<List<MeasureUnitDto>> GetMeasureUnitDto()
        {
            var measureUnitDtoList = RedisClusterHelper.Get<List<MeasureUnitDto>>("GetMeasureUnitDto");

            if (measureUnitDtoList == null)
            {
                lock (obj)
                {
                    if (measureUnitDtoList == null)
                    {
                        var measureUnitList = _measureUnitAppService.GetListAsync();
                        var tmpMeasureUnitDto = measureUnitList.Result.Select(m => new MeasureUnitDto
                        {
                            Id = m.Id,
                            UnitCode = m.UnitCode,
                        }).ToList();
                        RedisClusterHelper.Set("GetMeasureUnitDto", tmpMeasureUnitDto);
                        return tmpMeasureUnitDto;
                    }
                }
            }
            return measureUnitDtoList;
        }
    }
}
